<template>
    <div id="task3-view">
              <!-- 添加标题 -->
              <h1>中国新能源汽车品牌销量Top10</h1>
      <div class="brand-container">
        <div 
          v-for="(brand, index) in brands" 
          :key="index" 
          class="brand-module"
          @click="navigateToBrandDetail(brand.name)"
        >
          <img :src="brand.imageUrl" :alt="brand.name" class="brand-image" />
          <h3 class="brand-name">{{ brand.name }}</h3>
        </div>
      </div>
    </div>
  </template>
  
  <script>import axios from 'axios';
  
  export default {
    name: 'Task3View',
    data() {
      return {
        brands: [], // 初始化为空，等待数据加载
        // 图片映射表，直接使用外部URL，无需require
        imageMap: {
          '比亚迪': require('@/assets/比亚迪.jpg'),
          '特斯拉': require('@/assets/特斯拉.jpg'),
          '大众': require('@/assets/大众.jpg'),
          '丰田': require('@/assets/丰田.jpg'),
          '广汽埃安': require("@/assets/广汽埃安.jpg"),
          '蔚来': require("@/assets/蔚来.jpg"),
          '理想': require("@/assets/理想.jpg"),
          '长安': require("@/assets/长安.jpg"),
          '奇瑞': require("@/assets/奇瑞.jpg"),
          '五菱汽车':require("@/assets/五菱.jpg"),
        },
      };
    },
    async mounted() {
      try {
        // 发起请求获取品牌名列表
        const response = await axios.get('/api/task3/top10brand'); // 假定的API路径
        console.log(response.data);
        // 确保响应数据是一个数组再进行映射操作
        if (Array.isArray(response.data.data)) {
      // 使用品牌名列表和映射表构造完整的品牌信息列表
      this.brands = response.data.data.map(name => ({
        name,
        imageUrl: this.imageMap[name] || 'src\\assets\\比亚迪.jpg', // 默认图片URL
      }));
    } else {
      console.error("Unexpected data format in 'data' field from API. Expected an array but received:", response.data.data);
    }
  } catch (error) {
    console.error("Error fetching brands:", error);
  }
},
    methods: {
      navigateToBrandDetail(brandName) {
        this.$router.push({ name: 'BrandDetailByName', params: { brandName } });
      },
    },
  };
  </script>
  
  
  <style scoped>
  #task3-view {
  text-align: center;
}

.brand-container {
    display: grid;
  /* 明确指定两行 */
  grid-template-rows: repeat(2, 1fr);
  /* 固定每行五个模块，自动换行 */
  grid-template-columns: repeat(5, minmax(200px, 1fr));
  gap: 1rem;
  padding: 2rem;
  justify-content: center;
  /* 确保自动换行到下一行 */
  grid-auto-flow: row dense;
}

.brand-module {
  cursor: pointer;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.brand-image {
  width: 100%;
  height: auto;
  object-fit: cover;
}

.brand-name {
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  text-align: center;
  font-weight: bold;
}
  </style>
  